<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMenu, ElMenuItem, ElInput, ElButton, ElIcon, ElAvatar } from 'element-plus'
import { Search, User, HomeFilled, Grid, Avatar, Menu, Bell, Monitor } from '@element-plus/icons-vue' // 将 Setting 改为 Monitor
import { useCartStore } from '@/stores/cart' // 导入购物车 store
import useUserInfoStore from '@/stores/userInfo.js' // 导入用户信息 store
import { useTokenStore } from '@/stores/token.js' // 导入token store
import logo from '@/assets/images/logo.png' // 导入logo图片
import defaultAvatar from '@/assets/images/default.png' // 导入默认头像
import { userInfoService,userTypeService} from '@/api/user.js'
import { getUnreadCount } from '@/api/message.js'


const router = useRouter()
const cartStore = useCartStore()
const userInfoStore = useUserInfoStore()
const tokenStore = useTokenStore()
const searchQuery = ref('')
const unreadCount = ref(0)

// 计算属性：判断用户是否登录 - 基于token和用户信息
const isLoggedIn = computed(() => !!tokenStore.token && !!userInfoStore.info.nickName)
// 计算属性：获取用户名 (如果已登录)
const username = computed(() => isLoggedIn.value ? userInfoStore.info.nickName : '未登录')
// 计算属性：获取用户头像 (如果已登录)
const userAvatar = computed(() => isLoggedIn.value ? userInfoStore.info.profilePicture : defaultAvatar)
// 获取用户的类型
const getUserType = async () => {
  const result = await userTypeService()
  userInfoStore.setUserType(result.data)
}

// 只有在用户已登录时才获取用户类型
if(isLoggedIn.value){
  getUserType()
}

const isAdmin = computed(() => userInfoStore.userType?.id === '10000')

// 通用导航函数：需要登录的页面
const navigateToProtectedPage = (path) => {
  if (isLoggedIn.value) {
    router.push(path)
  } else {
    router.push('/login')
  }
}

const navigateToHome = () => {
  router.push('/home')
}

const navigateToUser = () => {
  navigateToProtectedPage('/home/user')
}

const navigateToMessages = () => {
  navigateToProtectedPage('/home/messages')
}

const navigateToAdmin = () => {
  router.push('/admin')
}

const handleSearch = () => {
  const query = searchQuery.value.trim()
  if (query) {
    router.push({
      path: '/home/search',
      query: { q: query }
    })
  }
}

const handleKeyPress = (event) => {
  if (event.key === 'Enter') {
    handleSearch()
  }
}

// 获取未读消息数量
const fetchUnreadCount = async () => {
  try {
    // const result = await getUnreadCount()
    // unreadCount.value = result.data
  } catch (error) {
    // console.error('获取未读消息数量失败:', error)
  }
}

onMounted(() => {
  fetchUnreadCount()
})
</script>

<template>
  <header class="header">
    <div class="nav-container">
      <div class="nav-left">
        <div class="logo" @click="navigateToHome">
          <img :src="logo" alt="Pardo Mall" class="logo-image">
        </div>
      </div>
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索商品"
          :prefix-icon="Search"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>
      <div class="nav-right">
        <div class="user-actions">
          <div v-if="isAdmin" class="admin-link" @click="navigateToAdmin">
            <el-icon class="admin-icon">
              <Monitor />
            </el-icon>
            <span class="admin-text">返回后台</span>
          </div>
          <div class="message-icon-wrapper" @click="navigateToMessages">
            <el-icon class="message-icon">
              <Bell />
            </el-icon>
            <el-badge v-if="unreadCount > 0" :value="unreadCount" class="message-badge" />
          </div>
          <span class="login-status-text" @click="navigateToUser">
            {{ username }}
          </span>
          <el-avatar 
            :size="32"
            :src="userAvatar"
            @click="navigateToUser"
          />
        </div>
      </div>
    </div>
  </header>
</template>

<style scoped>
/* 顶部导航栏样式 */
.header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.logo-image {
  height: 40px;
  width: auto;
}

.search-box {
  flex: 1;
  max-width: 500px;
  margin: 0 40px;
}

.search-input {
  width: 100%;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-menu {
  border-bottom: none;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.login-status-text {
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  white-space: nowrap;
}

.login-status-text:hover {
  color: #409EFF;
}

.el-avatar {
  cursor: pointer;
  transition: transform 0.2s;
}

.el-avatar:hover {
  transform: scale(1.1);
}

.message-icon {
  font-size: 20px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
}

.message-icon:hover {
  color: #409EFF;
  transform: scale(1.1);
}

.admin-icon {
  font-size: 20px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s ease;
}

.admin-icon:hover {
  color: #409EFF;
  transform: scale(1.1);
}

/* 暗黑模式样式 */
:root.dark .header {
  background-color: #333;
  box-shadow: 0 2px 8px rgba(255,255,255,0.1);
}

:root.dark .message-icon {
  color: #909399;
}

:root.dark .message-icon:hover {
  color: #409EFF;
}

:root.dark .admin-icon {
  color: #909399;
}

:root.dark .admin-icon:hover {
  color: #409EFF;
}

.admin-link {
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-right: 10px;
  padding: 4px 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.admin-link:hover {
  color: #409EFF;
  border-color: #409EFF;
}

.admin-text {
  font-size: 14px;
  color: #606266;
  margin-left: 4px;
}

.admin-link:hover .admin-icon,
.admin-link:hover .admin-text {
  color: #409EFF;
}

:root.dark .admin-link {
  border-color: #4c4d4f;
}

:root.dark .admin-icon,
:root.dark .admin-text {
  color: #909399;
}

:root.dark .admin-link:hover {
  border-color: #409EFF;
}

:root.dark .admin-link:hover .admin-icon,
:root.dark .admin-link:hover .admin-text {
  color: #409EFF;
}

.message-icon-wrapper {
  position: relative;
  cursor: pointer;
}

.message-badge {
  position: absolute;
  top: -8px;
  right: -8px;
}
</style> 